package edu.ubb.remeye.encodings.encoders.png;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import edu.ubb.remeye.encodings.encoders.ImageEncoder;
import edu.ubb.remeye.exception.ImageEncodingException;
import edu.ubb.remeye.gui.internationalization.LanguageManager;

/**
 * PNG format image encoder.
 * 
 * @author Andrew Ianicicau
 *
 */
public class PNGImageEncoder implements ImageEncoder {

	///////////////////////////////////////////////////////////////////////////////////
	////		METHODS - PNGImageEncoder 
	///////////////////////////////////////////////////////////////////////////////////

	@Override
	public byte[] encode(Image image) throws ImageEncodingException {
		byte[] encodedImage = null;
		try {
			encodedImage = getPNGImage(image);
		} catch (IOException e) {
			String errorMessage = "PNG " + LanguageManager.getLanguageManager().getText("encodefailed");
			throw new ImageEncodingException(errorMessage);
		}
		return encodedImage;
	}
	
	/**
	 * Returns a byte array of a buffered image converted into PNG format.
	 * @param image Buffered image to convert.
	 * @return Byte array of PNG format image.
	 * @throws IOException
	 */
	private byte[] getPNGImage(Image image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write((RenderedImage) image, "PNG", baos);
        return baos.toByteArray();
    }

}
